import pymysql
import configparser
from werkzeug.security import generate_password_hash

# 从配置文件获取数据库配置
config = configparser.ConfigParser()
config.read('config.ini', encoding='utf-8')

MYSQL_HOST = config['database']['HOST']
MYSQL_USER = config['database']['USER']
MYSQL_PASSWORD = config['database']['PASSWORD']
MYSQL_DB = config['database']['DB']
MYSQL_PORT = int(config['database']['PORT'])

# 数据库连接函数
def get_db_connection():
    try:
        connection = pymysql.connect(
            host=MYSQL_HOST,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            database=MYSQL_DB,
            port=MYSQL_PORT,
            cursorclass=pymysql.cursors.DictCursor
        )
        return connection
    except pymysql.MySQLError as e:
        print(f"数据库连接错误: {e}")
        raise e

def reset_admin_password():
    connection = None
    cursor = None
    try:
        connection = get_db_connection()
        cursor = connection.cursor()
        
        # 生成新密码哈希
        new_password = 'admin'
        password_hash = generate_password_hash(new_password)
        
        # 更新admin用户密码
        sql = "UPDATE users SET password_hash = %s WHERE username = %s"
        cursor.execute(sql, (password_hash, 'admin'))
        connection.commit()
        
        if cursor.rowcount > 0:
            print("admin用户密码已成功重置为: admin")
        else:
            print("未找到admin用户，请检查数据库")
            
    except Exception as e:
        print(f"重置密码时出错: {e}")
        if connection:
            connection.rollback()
    finally:
        if cursor:
            cursor.close()
        if connection:
            connection.close()

if __name__ == "__main__":
    reset_admin_password()